/**
 * adz云对象请求封装
 * o.url {String} 请求地址
 * o.data {Object} 请求参数
 * o.type {String||Number} 提示窗口提示 0请求前后不提示  1请求前提示  2请求后提示 3请求前后提示
 * o.errorType { String||Number } 请求出错后是否提示 0不提示  1提示
 * o.bMsg {String} 请求前提示 type为1或3
 * o.eMsg {String} 请求后提示 type为2或3
 * o.back {Boolean} 请求结束是否返回 默认false
 * o.successCode {Number} 请求成功后的code 默认0
 * o.loginLoseCode {Number} token失效的code 默认30000
 */
const adz = uniCloud.importObject('a-dz', { customUI: true });
const request = (o) => {
	return new Promise(async (resolve, reject) => {
		let {
			name,
			data = {},
			type = 0,
			errorType = 1,
			bMsg = '',
			eMsg = '请求成功',
			successCode = 0,
			loginLoseCode = 30000
		} = o;
		if (type == 1 || type == 3) {
			setTimeout(() => {
				uni.showLoading({
					title: bMsg,
					mask: true
				});
			}, 10)
		}
		if (getApp().globalData.deviceId) {
			data.deviceId = getApp().globalData.deviceId;
		}
		try {
			const result = await adz[name](data);
			switch (result.code) {
				case successCode:
					setTimeout(() => {
						if (type == 2 || type == 3) {
							getApp().globalData.notify({
								message: eMsg
							})
						}
						resolve(result);
					}, 100)
					break;
				case 1:
					setTimeout(() => {
						uni.showModal({
							title: result.title ? result.title : '',
							content: result.msg,
							showCancel: false
						})
						resolve(result);
					}, 100)
					break;
				case loginLoseCode:
					getApp().globalData.notify({
						type: 'error',
						message: '登录已失效，请重新登录！'
					})
					uni.removeStorageSync('uni-id-pages-userInfo');
					uni.removeStorageSync('uni_id_token');
					uni.removeStorageSync('uni_id_token_expired');
					setTimeout(() => {
						location.reload();
					}, 300)
					break;
				case -2:
					setTimeout(() => {
						getApp().globalData.notify({
							type: 'error',
							message: result.msg
						})
						reject(result);
					}, 100)
					break;
				case -3:
					setTimeout(() => {
						uni.$emit('openMsg', {
							title: result.title ? result.title : '',
							content: result.msg,
							showCancel: false
						})
						reject(result);
					}, 100)
					break;
				case -100: //不是会员
					uni.$emit('openVip');
					reject(result);
					break;
				default:
					setTimeout(() => {
						if (type == 2 || type == 3) {
							getApp().globalData.notify({
								type: 'error',
								message: result.msg
							})
						}
						reject(result);
					}, 100)
					break;
			}
		} catch (err) {
			console.error('请求异常：', err);
			if (JSON.stringify(err).indexOf('超时') > -1) {
				uni.$emit('openMsg', {
					title: '提示',
					content: `请求超时，联系管理员微信：<br>${getApp().globalData.configData.customer_wx}`,
					showCancel: false
				})
			} else {
				if (errorType) uni.$emit('openMsg', {
					title: '提示',
					content: '请求异常，请检查网络',
					showCancel: false
				})
			}
			reject(err);
		}
		setTimeout(() => {
			uni.hideLoading();
		}, 20)
	})
}
export {
	request
};